package report

import (
	"../common"
	"../web"
	"encoding/json"
	"strconv"
	"strings"
	"time"
)

type QueryOperObj struct {
	common.BaseHandler
}

type QueryOperDetailObj struct {
	common.BaseHandler
}

type QueryOperPageObj struct {
	common.BaseHandler
}

func (self *QueryOperObj) Prepare() {}

func (self *QueryOperObj) ParameterCheck() bool {
	c_begin := strings.TrimSpace(self.Ctx.Params["fromdate"])
	c_end := strings.TrimSpace(self.Ctx.Params["todate"])
	s_oper := strings.TrimSpace(self.Ctx.Params["oper"])
	if c_begin == "" {
		return false
	}
	s_begin, err := time.Parse("2006-01-02 15:04:05", c_begin)
	if err != nil {
		self.TmplData["error"] = common.GetText(self.Lang, "Query Begin Date is invalid.")
		return false
	}
	if len(c_begin) != 19 {
		self.TmplData["error"] = common.GetText(self.Lang, "Query Begin Date is invalid.")
		return false
	}
	if c_end == "" {
		return false
	}
	s_end, err := time.Parse("2006-01-02 15:04:05", c_end)
	if err != nil {
		self.TmplData["error"] = common.GetText(self.Lang, "Query End Date is invalid.")
		return false
	}
	if len(c_end) != 19 {
		self.TmplData["error"] = common.GetText(self.Lang, "Query End Date is invalid.")
		return false
	}
	if s_oper == "" {
		return false
	}
	if c_begin == c_end {
		self.TmplData["error"] = common.GetText(self.Lang, "The selected time period is not a valid interval.")
		return false
	}
	if s_begin.After(s_end) {
		s_begin, s_end = s_end, s_begin
		c_begin, c_end = c_end, c_begin
	}
	if s_begin.Add(3600 * 24 * 180 * time.Second).Before(s_end) {
		self.TmplData["error"] = common.GetText(self.Lang, "Date interval can select up to 180 days.")
		return false
	}

	c_begin = s_begin.Format("2006-01-02 15:04:05")
	c_end = s_end.Format("2006-01-02 15:04:05")

	self.Sqlparas = append(self.Sqlparas, s_oper)
	self.Sqlparas = append(self.Sqlparas, c_begin)
	self.Sqlparas = append(self.Sqlparas, c_end)

	self.TmplData["begindate"] = c_begin
	self.TmplData["enddate"] = c_end
	self.TmplData["operator"] = s_oper

	return true
}

func (self *QueryOperObj) SqlQueryExecute() {
	oper_lst := *common.FetchAllRowsPtr(
		`SELECT CURR_STATION, COUNT(CURR_STATION) FROM SFC_SSNFLOW(NOLOCK) 
          WHERE MODIFYBY = ?  
            AND MODIFYDATE BETWEEN ? AND ? 
          GROUP BY CURR_STATION`,
		self.Usr.Conn, new(common.OperCount), self.Sqlparas...)

	self.TmplData["oper_lst"] = oper_lst
}

func QueryOperHandler(ctx *web.Context) {
	self := new(QueryOperObj)
	self.Ctx = ctx
	self.Html = "querybyoper.html"
	self.Rightlist = []string{"querybyoper"}
	self.DoQuery(self)
}

func (self *QueryOperDetailObj) ParameterCheck() bool {
	s_fd := self.Ctx.Params["fd"] // begin date
	s_td := self.Ctx.Params["td"] // end date
	s_st := self.Ctx.Params["st"] // station
	s_op := self.Ctx.Params["op"] // operator

	if s_fd == "" || s_td == "" || s_st == "" || s_op == "" {
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_op)
	self.Sqlparas = append(self.Sqlparas, s_fd)
	self.Sqlparas = append(self.Sqlparas, s_td)
	self.Sqlparas = append(self.Sqlparas, s_st)

	self.TmplData["fromdate"] = s_fd
	self.TmplData["todate"] = s_td
	self.TmplData["operator"] = s_op
	self.TmplData["station"] = s_st
	self.TmplData["curr_page"] = "1"

	return true
}

func (self *QueryOperDetailObj) SqlQueryExecute() {
	ssn_main := *common.FetchAllRowsPtr(
		`SELECT TOP 10 ROW_NUMBER() OVER(ORDER BY B.SSN_NO) AS AUTOID,A.WONO,B.SSN_NO,
				 B.CURR_STATION,B.RESULT,CONVERT(CHAR(23),B.MODIFYDATE,121),ISNULL(C.NAME,'') AS OPER
           FROM SFC_SSN A(NOLOCK), SFC_SSNFLOW B(NOLOCK), ShopFloorControl.dbo.SFC_EMPLOYEE C(NOLOCK) 
          WHERE B.MODIFYBY=? 
            AND B.MODIFYDATE BETWEEN ? AND ? 
            AND B.CURR_STATION=? 
            AND A.SSN_NO=B.SSN_NO
            AND B.MODIFYBY=C.ID`,
		self.Usr.Conn, new(common.OperDetail), self.Sqlparas...)

	iRtnData := *common.FetchOneRowPtr(
		`SELECT COUNT(SSN_NO)
           FROM SFC_SSNFLOW(NOLOCK) 
          WHERE MODIFYBY=? 
            AND MODIFYDATE BETWEEN ? AND ? 
            AND CURR_STATION=?`,
		self.Usr.Conn, new(common.RecCount), self.Sqlparas...)
	recnum := iRtnData.(common.RecCount).Number
	total_id := recnum / 10
	if recnum%10 > 0 {
		total_id = total_id + 1
	}

	self.TmplData["ssn_main"] = ssn_main
	self.TmplData["total_page"] = total_id
}

func QueryOperDetailHandler(ctx *web.Context) {
	self := new(QueryOperDetailObj)
	self.Ctx = ctx
	self.Html = "querybyoperdetail.html"
	self.Rightlist = []string{"querybyoper"}
	self.DoQueryUrl(self)
}

func (self *QueryOperPageObj) ParameterCheck() bool {
	s_page := self.Ctx.Params["pageid"] // current page
	s_fd := self.Ctx.Params["fd"]       // begin date
	s_td := self.Ctx.Params["td"]       // end date
	s_st := self.Ctx.Params["st"]       // station
	s_op := self.Ctx.Params["op"]       // operator
	if s_fd == "" || s_td == "" || s_st == "" || s_op == "" {
		return false
	}
	pageid, err := strconv.Atoi(s_page)
	if err != nil {
		return false
	}

	idx := 10 * (pageid - 1)

	self.Sqlparas = append(self.Sqlparas, s_op)
	self.Sqlparas = append(self.Sqlparas, s_fd)
	self.Sqlparas = append(self.Sqlparas, s_td)
	self.Sqlparas = append(self.Sqlparas, s_st)
	self.Sqlparas = append(self.Sqlparas, idx)

	return true
}

func (self *QueryOperPageObj) SqlQueryExecute() {
	ssn_main := *common.FetchAllRowsPtr(
		`SELECT TOP 10 A.AUTOID, A.WONO, A.SSN_NO, A.CURR_STATION, 
                 A.RESULT, CONVERT(CHAR(23), A.MODIFYDATE, 121), A.OPER
          FROM
              (
                SELECT ROW_NUMBER() OVER(ORDER BY B.SSN_NO) AS AUTOID, A.WONO, 
                        B.SSN_NO, B.CURR_STATION, B.RESULT, B.MODIFYDATE, ISNULL(C.NAME, '') AS OPER
                  FROM SFC_SSN A(NOLOCK), SFC_SSNFLOW B(NOLOCK), ShopFloorControl.dbo.SFC_EMPLOYEE C(NOLOCK) 
                 WHERE B.MODIFYBY=?  
                   AND B.MODIFYDATE BETWEEN ? AND ? 
                   AND B.CURR_STATION=? 
                   AND A.SSN_NO=B.SSN_NO
                   AND B.MODIFYBY=C.ID
              ) A
          WHERE A.AUTOID > ?`,
		self.Usr.Conn, new(common.OperDetail), self.Sqlparas...)

	dict_js, _ := json.Marshal(map[string]interface{}{"details": ssn_main, "lang": self.Lang})
	self.Ctx.ResponseWriter.Write(dict_js)
}

func SplitOperByPageHandler(ctx *web.Context) {
	self := new(QueryOperPageObj)
	self.Ctx = ctx
	self.DoJsonQuery(self)
}
